package com.eboss.sbs.activity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;

import com.eboss.sbs.R;
import com.eboss.sbs.activity.base.BaseActivity;
import com.eboss.sbs.enums.EnumConsts;
import com.eboss.sbs.http.API;
import com.eboss.sbs.http.HttpCallback;
import com.eboss.sbs.model.CaculateMoneyEntity;
import com.eboss.sbs.model.UploadResultEntity;
import com.eboss.sbs.model.db.OrderDetail;
import com.google.gson.reflect.TypeToken;
import com.mytools.tool.utils.LocalParasUtils;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.views.MyDialog;

import org.litepal.crud.DataSupport;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PayCardActivity extends BaseActivity {
	
	private CaculateMoneyEntity caculateMoneyEntity;
	private String password;
	private String couponSns;
	private int pointAmount;
	
	private int real_money = -1;
	
	private int scanPayType = EnumConsts.ScanPayType.SQB.getType();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mActivity = this;
		setContentView(R.layout.activity_pay_card);
		super.onCreate(savedInstanceState);
		
		scanPayType = mApp.getLoginEntity().getScanPayType();
		
		password = getIntent().getStringExtra("password");
		couponSns = getIntent().getStringExtra("couponSns");
		pointAmount = getIntent().getIntExtra("pointAmount", 0);
		caculateMoneyEntity = (CaculateMoneyEntity) getIntent().getSerializableExtra(PayCashActivity.CACULATE_MONEY_ENTITY);
		if(caculateMoneyEntity==null){toast("金额参数错误");finish();return;}
		real_money = caculateMoneyEntity.getRealMoney();
		
		initView();
	}
	
	private void initView(){
		setTvText(R.id.tv_title, "刷卡记账");
		findViewById(R.id.titleback_btn_back).setOnClickListener(this);
		findViewById(R.id.btn_submit).setOnClickListener(this);
		setTvText(R.id.tv_real_money, StringUtil.getMoneyString(real_money));
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.titleback_btn_back:
				finish();
				break;
			case R.id.btn_submit:
				doSubmit_pre();
				break;
			default:break;
		}
		super.onClick(v);
	}
	
	private void doSubmit_pre(){
		MyDialog dialog;
		MyDialog.Builder builder = new MyDialog.Builder(this);
		builder.setTitle("提示");
		builder.setMessage("确认已经收到现金 "+StringUtil.getMoneyString(real_money)+" 元");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				doSubmit();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				dialog.dismiss();
			}
		});
//		builder.create().show();
		dialog=builder.create();
//		dialog.setCancelable(false);
		dialog.show();
	}
	
	private void doSubmit(){
		final String client_sn = PayChannelChooseActivity.getNewClientSn(mActivity, EnumConsts.SqbPayChannel.CARD_MEMO.getType(), scanPayType);
		
		long t = new Date().getTime();
		saveLocalTradeDetail(t, client_sn);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sid", mApp.getLoginEntity().getSid());
		String memberCardNo = caculateMoneyEntity.getMemberCardNo();
		if(!StringUtil.isNull(memberCardNo)){params.put("cardNo", memberCardNo);}
		else{params.put("cardNo", "");}
		if(!StringUtil.isNull(password)){params.put("password", password);}
		else{params.put("password", "");}
		if(!StringUtil.isNull(couponSns)){params.put("couponSns", couponSns);}
		else{params.put("couponSns", "");}
		params.put("cash", caculateMoneyEntity.getRealMoney());
		params.put("bankAmount", "");
		params.put("couponCoverAmount", caculateMoneyEntity.getCouponCoverMoney());
		params.put("pointCoverAmount", caculateMoneyEntity.getPointCoverMoney());
		params.put("pointAmount", pointAmount);
		params.put("clientOrderNo", client_sn);
		
		//收钱吧
		if(scanPayType== EnumConsts.ScanPayType.SQB.getType()){
			params.put("activateCode", LocalParasUtils.getActivateCode(this));
			params.put("merchantNo", LocalParasUtils.getMerchantNo(this));
		}
		//富友
		else if(scanPayType== EnumConsts.ScanPayType.FUYOU.getType()){
			params.put("activateCode", mApp.getLoginEntity().getActivateCode());
			params.put("merchantNo", mApp.getLoginEntity().getFyMerchantNo());
		}
		
		params.put("t", t);
		params.put("transNo", "");
		params.put("authCode", "");
		TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); 
		String imei = tm.getDeviceId();
		params.put("serialNum", imei);
		params.put("payType", EnumConsts.SqbPayChannel.CARD_MEMO.getType());
		
		API.http_post(this, API.TRADE_LOG_UPLOAD, params, new HttpCallback<UploadResultEntity>(this) {
			@Override
			public void onSuccess(int statusCode, UploadResultEntity data) {
				updateOrderDetail(client_sn, data);
				openConfirmDialog();
			}

			@Override
			public void onFailure(int statusCode, String message) {
				openConfirmDialog();
				super.onFailure(statusCode, message);
			}
			
			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public TypeToken getTypeToken() {
				return new TypeToken<UploadResultEntity>() {};
			}
		});
	}
	
	private void updateOrderDetail(String clientOrderNo, UploadResultEntity data) {
		ContentValues cv = new ContentValues();
		String point_url = data.getPoint_url();
		String coupon_url = data.getCoupon();
		cv.put("point_url", StringUtil.isNull(point_url)?"":point_url);
		cv.put("coupon_url", StringUtil.isNull(coupon_url)?"":coupon_url);
		int point = data.getPoint();
		int pointCurrent = data.getPointCurrent();
		cv.put("point", point);
		cv.put("pointCurrent", pointCurrent);
		
		DataSupport.updateAll(OrderDetail.class, cv, "tradeOrderNo = ?", clientOrderNo);
	}
	
	private void saveLocalTradeDetail(long t, String tradeOrderNo){
		
		OrderDetail orderDetail = new OrderDetail();
		orderDetail.setTradeOrderNo(tradeOrderNo);
		orderDetail.setPayType(EnumConsts.SqbPayChannel.CARD_MEMO.getType());
		orderDetail.setTerminalSn(""+LocalParasUtils.getMerchantNo(this));
		orderDetail.setState(EnumConsts.SqbPayState.SUCCESS.getType());
		orderDetail.setTradeMoney(caculateMoneyEntity.getTradeMoney());
		orderDetail.setRealMoney(caculateMoneyEntity.getRealMoney());
		orderDetail.setMemberName(caculateMoneyEntity.getMemberName());
		orderDetail.setTerminalName(LocalParasUtils.getTerminalName(mActivity));  //激活时拿到
		//orderDetail.setPointCost(caculateMoneyEntity.getPointCoverMoney());
		
		int couponCoverMoney = caculateMoneyEntity.getCouponCoverMoney();
		int pointCoverMoney = caculateMoneyEntity.getPointCoverMoney();
		String couponString = couponCoverMoney==0?"":("优惠券抵消"+StringUtil.getMoneyString(couponCoverMoney)+"元;");
		String pointString = pointCoverMoney==0?"":("积分抵消"+StringUtil.getMoneyString(pointCoverMoney)+"元;");
		if(!StringUtil.isNull(couponString)||!StringUtil.isNull(pointString)) orderDetail.setBenefit(pointString+couponString);
		
		orderDetail.setTradeTime(t);
		if(!StringUtil.isNull(password)){orderDetail.setPassword(password);}
		if(!StringUtil.isNull(couponSns)){orderDetail.setCouponSns(couponSns);}
		String memberCardNo = caculateMoneyEntity.getMemberCardNo();
		if(!StringUtil.isNull(memberCardNo)){orderDetail.setCardNo(memberCardNo);}
		orderDetail.setPointAmount(pointAmount);
		
		orderDetail.setCash(caculateMoneyEntity.getRealMoney());
		orderDetail.setBankAmount(0);
		
		//收钱吧
		if(scanPayType== EnumConsts.ScanPayType.SQB.getType()){
			orderDetail.setTerminalSn(LocalParasUtils.getActivateCode(mActivity));
			orderDetail.setMerchantNo(LocalParasUtils.getMerchantNo(mActivity));
			orderDetail.setActivateCode(LocalParasUtils.getActivateCode(mActivity));
			orderDetail.setTerminalName(LocalParasUtils.getTerminalName(mActivity));
		}
		//富友
		else if(scanPayType== EnumConsts.ScanPayType.FUYOU.getType()){
			orderDetail.setTerminalSn(mApp.getLoginEntity().getFyMerchantNo());
			orderDetail.setMerchantNo(mApp.getLoginEntity().getFyMerchantNo());
			orderDetail.setActivateCode(mApp.getLoginEntity().getActivateCode());
			orderDetail.setTerminalName(mApp.getLoginEntity().getFyMerchantName());
		}

		TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); 
		orderDetail.setSerialNum(tm.getDeviceId());
		orderDetail.save();
	}
	
	private void openConfirmDialog(){
		MyDialog.Builder builder = new MyDialog.Builder(this);
		builder.setTitle("提示");
		builder.setMessage("现金收款成功！");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				finish();
				startActivity(new Intent(mActivity, PayMoneyInputActivity.class));
				
				Intent intent = new Intent(PayMoneyInputActivity.RECEIVER_CLEAN_DATA_TAG);
				intent.putExtra(PayMoneyInputActivity.NOTIFY_CODE_TAG, PayMoneyInputActivity.CLEAN_DATA);
		        sendBroadcast(intent); 
				
			}
		});
		builder.create().show();
	}

}
